package com.gqj.elec.controller;

import com.alibaba.fastjson2.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.common.utils.sign.Base64;
import com.gqj.elec.domain.ElecMaterialIndetail;
import com.gqj.elec.domain.ElecMaterialIninfo;
import com.gqj.elec.domain.vo.ElecMaterialIninfoVo;
import com.gqj.elec.service.IElecMaterialIndetailService;
import com.gqj.elec.service.IElecMaterialIninfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * 物资入库Controller
 *
 * @author lxq
 * @date 2023-12-17
 */
@RestController
@RequestMapping("/elec/elecMaterialIninfo")
public class ElecMaterialIninfoController extends BaseController {
    @Autowired
    private IElecMaterialIninfoService elecMaterialIninfoService;
    @Autowired
    private IElecMaterialIndetailService elecMaterialIndetailService;
    @Value("${downloadPath}")
    private String downloadPath;

    /**
     * 查询物资入库列表
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialIninfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElecMaterialIninfo elecMaterialIninfo) {
        startPage();
        elecMaterialIninfo.setDelFlag("0");
        List<ElecMaterialIninfo> list = elecMaterialIninfoService.selectElecMaterialIninfoList(elecMaterialIninfo);
        return getDataTable(list);
    }

    /**
     * 导出物资入库列表
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialIninfo:export')")
    @Log(title = "物资入库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElecMaterialIninfo elecMaterialIninfo) {
        elecMaterialIninfo.setDelFlag("0");
        List<ElecMaterialIninfo> list = elecMaterialIninfoService.selectElecMaterialIninfoList(elecMaterialIninfo);
        ExcelUtil<ElecMaterialIninfo> util = new ExcelUtil<ElecMaterialIninfo>(ElecMaterialIninfo.class);
        util.exportExcel(response, list, "物资入库数据");
    }

    /**
     * 获取物资入库详细信息
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialIninfo:query')")
    @GetMapping(value = "/{inId}")
    public AjaxResult getInfo(@PathVariable("inId") Long inId) {
        return AjaxResult.success(elecMaterialIninfoService.selectElecMaterialIninfoByInId(inId));
    }

    /**
     * 新增物资入库
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialIninfo:add')")
    @Log(title = "物资入库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElecMaterialIninfo elecMaterialIninfo) {
        if (null == elecMaterialIninfo.getElecMaterialList() || elecMaterialIninfo.getElecMaterialList().size() <= 0) {
            return AjaxResult.error("工器具列表为空，不允许新增");
        }
        elecMaterialIninfo.setCreateBy(getUsername());
        return toAjax(elecMaterialIninfoService.insertElecMaterialIninfo(elecMaterialIninfo));
    }

    /**
     * 修改物资入库
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialIninfo:edit')")
    @Log(title = "物资入库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElecMaterialIninfo elecMaterialIninfo) {
        ElecMaterialIninfo temp = elecMaterialIninfoService.selectElecMaterialIninfoByInId(elecMaterialIninfo.getInId());
        if (!UserConstants.BILL_ISDEL.equals(temp.getInStatus())) {
            return AjaxResult.error("单据不是录入状态，不允许修改");
        }
        if (null == elecMaterialIninfo.getElecMaterialList() || elecMaterialIninfo.getElecMaterialList().size() <= 0) {
            return AjaxResult.error("工器具列表为空，不允许修改");
        }
        elecMaterialIninfo.setUpdateBy(getUsername());
        return toAjax(elecMaterialIninfoService.updateElecMaterialIninfo(elecMaterialIninfo));
    }

    /**
     * 删除物资入库
     */
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialIninfo:remove')")
    @Log(title = "物资入库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{inIds}")
    public AjaxResult remove(@PathVariable Long[] inIds) {
        for (Long inId : inIds) {
            ElecMaterialIninfo temp = elecMaterialIninfoService.selectElecMaterialIninfoByInId(inId);
            if (!UserConstants.BILL_ISDEL.equals(temp.getInStatus())) {
                return AjaxResult.error("单据" + temp.getBatchNumber() + "不是录入状态，不允许删除");
            }
        }
        return toAjax(elecMaterialIninfoService.deleteElecMaterialIninfoByInIds(inIds));
    }

    /**
     * 查看照片
     */
    @GetMapping("/searchImg")
    public AjaxResult searchImg(ElecMaterialIninfo elecMaterialIninfo) {

        ElecMaterialIninfo entity = elecMaterialIninfoService.selectElecMaterialIninfoByInId(elecMaterialIninfo.getInId());
        if (null == entity.getFacePicuture() || "".equals(entity.getFacePicuture())) {
            return AjaxResult.success(entity);
        }

        String path = "D:/gwelec-zp/" + entity.getFacePicuture();
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        entity.setFacePicuture("data:image/gif;base64," + Base64.encode(data));
        return AjaxResult.success(entity);
    }

    /**
     * 下载工器具json文件
     */
    @ApiOperation("下载工器具json文件")
    @PreAuthorize("@ss.hasPermi('elec:elecMaterialIninfo:downloadJsonElecMaterialInInfo')")
    @GetMapping("/downloadJsonElecMaterialInInfo")
    public AjaxResult downloadJsonElecMaterialInInfo(ElecMaterialIninfo elecMaterialIninfo) {
        elecMaterialIninfo.setDelFlag("0");
        List<ElecMaterialIninfo> mt = elecMaterialIninfoService.selectElecMaterialIninfoList(elecMaterialIninfo);
        ElecMaterialIndetail elecMaterialIndetail = new ElecMaterialIndetail();

        for (ElecMaterialIninfo elecMaterialIninfoTemp : mt) {
            elecMaterialIndetail.setInId(elecMaterialIninfoTemp.getInId());
            elecMaterialIninfoTemp.setElecMaterialIndetailList(elecMaterialIndetailService.selectElecMaterialIndetailList(elecMaterialIndetail));
        }

        List<ElecMaterialIninfoVo> vos = StorageUtil.copyList(mt, ElecMaterialIninfoVo::new);

        String orderNo = "工器具入库任务数据" + StorageUtil.getOrderNoTo12();
        String fileName = downloadPath + orderNo + ".json";
        String jsonStringAc = JSON.toJSONString(vos);
        File file = new File(fileName);
        try (FileWriter fileWriter = new FileWriter(file)) {
            fileWriter.write(jsonStringAc);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }
}
